package MathCore.Renders;

import MathCore.Expression;
import MathCore.Lexeme;
import MathCore.Operators.ArOperator;
import MathCore.Render;
import MathCore.Symbol;
import javax.microedition.lcdui.Graphics;

/**
 *
 * @author Александр
 */
public class Fraction extends Block
{
	public Stripe line1, line2;

	public Fraction()
	{
		line1 = line2 = null;
	}
	
	public Fraction(Stripe line1, Stripe line2)
	{
		set(line1, line2);
	}

	public void set(Stripe line1, Stripe line2)
	{
		this.line1 = line1;
		this.line2 = line2;

		line1.next = line2;
		line1.prev = null;
		line2.prev = line1;
		line2.next = null;

		line1.parent = line2.parent = this;

		line1.down = line2;
		line2.up = line1;
	}

	public int width()
	{
		if(line1 != null && line2 != null) return Math.max(line1.width(), line2.width());
		else return 0;
	}

	public int height()
	{
		if(line1 != null && line2 != null) return line1.height() + line2.height()+2;
		else return 0;
	}

	public int center()
	{
		if(line2 != null) return line2.height();
		else return 0;
	}

	public Block first()
	{
		return line1;
	}

	public Block last()
	{
		return line2;
	}

	public void draw(Graphics g, int x, int y, int style)
	{
		saveCoordinates(x, y, style);

		// смещаем координаты, учитывая стили сводим к HCENTER|VCENTER
		if(style(style, Block.TOP))		y += (height() - center());
		if(style(style, Block.BOTTOM))	y -= center();
		if(style(style, Block.RIGHT))	x -= width()/2;
		if(style(style, Block.LEFT))	x += width()/2;

		if(g != null)
		{
			g.setColor(Render.textColor);
			g.drawLine(x-width()/2, y, x+width()/2-1, y);
		}

		line1.draw(g, x, y-1, Block.HCENTER|Block.BOTTOM);
		line2.draw(g, x, y+1, Block.HCENTER|Block.TOP);
		
		if(Render.activeBlock == this && g != null && Render.useCursor)
		{
			g.setColor(Render.linkColor);
			g.drawLine(x+width()/2+1, y-line1.height()-1, x+width()/2+1, y+line2.height());
			g.drawLine(x-width()/2, y+line2.height(), x+width()/2, y+line2.height());
		}
	}

	public Block findLinked(Lexeme lex)
	{
		if(lex == link) return this;
		Block linked = line1.findLinked(lex);
		if(linked != null) return linked;
		linked = line2.findLinked(lex);
		return linked;
	}

	public String toString()
	{
		return "<fraction>";
	}

	public void extract(Expression exp)
	{
		exp.add(new Symbol(Symbol.LEFT_BRACE));
		exp.add(new Symbol(Symbol.LEFT_BRACE));
		line1.extract(exp);
		exp.add(new Symbol(Symbol.RIGHT_BRACE));
		exp.add(new ArOperator(ArOperator.DIVISION));
		exp.add(new Symbol(Symbol.LEFT_BRACE));
		line2.extract(exp);
		exp.add(new Symbol(Symbol.RIGHT_BRACE));
		exp.add(new Symbol(Symbol.RIGHT_BRACE));
	}

	public void parse()
	{
		if(line1 != null) line1.parse();
		if(line2 != null) line2.parse();
	}


}
